import json

from flask import Blueprint, request, jsonify
from flask_cors import CORS
from dao.StudentDao import StudentDao
from domain.DataConverter import DataConverter
from domain.student.Student import Student

student_blueprint = Blueprint('student', __name__)
CORS(student_blueprint)

# 查询学生信息
@student_blueprint.route('/getStudents', methods=['POST'])
def get_students():
    dao = StudentDao()
    dao.connect()
    pageNumber = request.json.get('pageNumber')
    pageSize = request.json.get('pageSize')
    results = dao.get_students_by_page(pageNumber, pageSize)
    students = DataConverter.convert_results_to_objects(results, Student)
    data = DataConverter.convert_objects_to_json(students)
    response = {'success': True, 'data': data}
    return jsonify(response)

# 新增或更新学生信息
@student_blueprint.route('/saveStudent', methods=['POST'])
def save_student():
    dao = StudentDao()
    dao.connect()
    id = request.json.get('id', 0)  # 默认值设为0，以便后续判断是否为更新操作
    name = request.json.get('name')
    age = request.json.get('age')
    grade = request.json.get('grade')

    if id > 0:
        row_count = dao.update_student(id, name, age, grade)
    else:
        row_count = dao.insert_student(name, age, grade)

    success = row_count > 0  # 根据受影响的行数判断操作是否成功

    response = {'success': success}
    return jsonify(response)

# 删除学生信息
@student_blueprint.route('/deleteStudent', methods=['GET'])  # 改为 GET 方法
def delete_student():
    dao = StudentDao()
    dao.connect()
    id = request.args.get('id', 0)  # 从 URL 中获取学生的 ID

    if id:
        id = int(id)  # 将 id 转换为整数
        row_count = dao.delete_student(id)

    success = row_count > 0  # 根据受影响的行数判断操作是否成功

    response = {'success': success}
    return jsonify(response)